import React, { useCallback, useEffect, useState } from 'react';
import { connect, ConnectedProps } from 'react-redux';

import { SOURCE } from 'utils/constant';
import { RootState } from 'src/app/rootReducer';
import { BodyContainer, Navbar, SearchList } from 'src/components';
import { searchAttrSelector, searchKeySelector, searchVideosSelector } from 'src/redux/search';
import { epicActions as searchEpics } from 'src/redux/search';
import { actions as otherActions } from 'src/redux/other';
import { actions as wactchActions } from 'src/redux/watch';

export const Web: React.FC<ReduxProps> = ({
  searchKey,
  videos,
  searchAttr,
  clearSearchDetails,
  loadAllSearchSource,
  gotoHome,
  setCancelAction,
  setWatchVideo,
  gotoPlay,
}) => {
  useEffect(() => {
    if (!searchKey) gotoHome();
  }, [gotoHome, searchKey]);

  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(searchAttr.page);

  useEffect(() => {
    if (videos.length === SOURCE.size) {
      setLoading(false);
    } else {
      setLoading(true);
    }
  }, [videos.length]);

  useEffect(() => {
    setPage(searchAttr.page);
  }, [searchAttr.page]);

  const pageChangeHandle = useCallback(
    (nextPage: number) => {
      setCancelAction('searcCancel');
      setLoading(true);
      clearSearchDetails();
      loadAllSearchSource('&wd=' + searchKey + '&pg=' + nextPage);
    },
    [clearSearchDetails, loadAllSearchSource, searchKey, setCancelAction],
  );

  const clickHandle = useCallback(
    (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
      const { from, id } = (e.target as HTMLElement).dataset;
      if (from && id) {
        const videoFrom = videos.find((v) => v.key === from);

        setWatchVideo(videoFrom!.value.value.find((v) => v.id === +id)!);
        gotoPlay();
      }
    },
    [gotoPlay, setWatchVideo, videos],
  );

  return (
    <React.Fragment>
      <Navbar needSource={false} />
      <BodyContainer>
        <SearchList
          loading={loading}
          videos={videos.filter((v) => v.value.value.length)}
          page={page}
          pagecount={searchAttr.pagecount}
          pageChangeHandle={pageChangeHandle}
          clickHandle={clickHandle}
        />
      </BodyContainer>
    </React.Fragment>
  );
};

const connector = connect(
  (state: RootState) => ({
    videos: searchVideosSelector(state),
    searchAttr: searchAttrSelector(state),
    searchKey: searchKeySelector(state),
  }),
  {
    loadAllSearchSource: searchEpics.loadAllSearchSource,
    clearSearchDetails: searchEpics.clearSearchDetails,
    gotoPlay: searchEpics.gotoPlay,
    gotoHome: searchEpics.gotoHome,
    setCancelAction: otherActions.setCancelAction,
    setWatchVideo: wactchActions.setWatchVideo,
  },
);

type ReduxProps = ConnectedProps<typeof connector>;
export const WebSerch = connector(Web);
